#include "ftpclientthread.h"

#include "../Global/commondefs.h"
#include "qftp.h"
#include "qurlinfo.h"
#include <QSettings>
#include <QFile>

FtpClientThread::FtpClientThread(const QStringList &dcms, const QString &dir, QObject *parent) :
    m_dcms(dcms),
    m_dir(dir),
    m_ftp(new QFtp(this)),
    QThread(parent)
{
    connect(m_ftp, SIGNAL(listInfo(QUrlInfo)), this, SLOT(onList(QUrlInfo)));
    connect(m_ftp, SIGNAL(stateChanged(int)), this, SLOT(onStateChanged(int)));
    connect(m_ftp, SIGNAL(done(bool)), this, SLOT(onFtpDone(bool)));
    connect(m_ftp, SIGNAL(commandFinished(int,bool)), this, SLOT(onCommandFinished(int,bool)));
}

FtpClientThread::~FtpClientThread()
{
    foreach (QIODevice *d, m_devs) {
        d->close();
        delete d;
    }
}

void FtpClientThread::run()
{
    QSettings s;
    QString host = s.value(NW_FTP_IP).toString();
    ushort port = s.value(NW_FTP_PORT, 21).toUInt();
    m_ftp->connectToHost(host, port);

    QString user = s.value(NW_FTP_USER).toString();
    QString pwd = s.value(NW_FTP_PWD).toString();
    m_ftp->login(user, pwd);

    foreach (const QString &dcm, m_dcms) {
        QString dest = dcm;
        dest.replace("\\", "/");
        dest = m_dir + "/" + dest.mid(dest.lastIndexOf("/")+1);
        if (QFile::exists(dest)) continue;
        QFile *f = new QFile(dest);
        m_devs << f;
        if (f->open(QIODevice::WriteOnly))
            m_ftp->get(dcm, f);
    }
    //ftp->list(m_hosCode + "/dicom/CT/2010/" + m_studyUid);
    exec();
}

void FtpClientThread::onList(const QUrlInfo &url)
{
    if (url.isDir()) {
        m_ftp->list(url.name());
    } else if (url.isFile()) {
        QFile *f = new QFile(m_dir+"/"+url.name(), this);
        m_devs << f;
        if (f->open(QIODevice::WriteOnly))
            m_ftp->get(url.name(), f);
    }
}

void FtpClientThread::onFtpDone(bool err)
{
    if (err) {
        emit error(m_ftp->errorString());
    }
    m_ftp->close();
}

void FtpClientThread::onCommandFinished(int id, bool err)
{
    Q_UNUSED(id);
    if (err) emit error(m_ftp->errorString());
}

void FtpClientThread::onStateChanged(int state)
{
    switch (state) {
    case QFtp::Unconnected:
        quit();
        break;
    case QFtp::HostLookup:

        break;
    case QFtp::Connecting:

        break;
    case QFtp::Connected:

        break;
    case QFtp::LoggedIn:

        break;
    case QFtp::Closing:
        //quit();
        break;
    }
}
